iT邦幫忙

2021 iThome 鐵人賽

DAY 25
0
自我挑戰組

IOS、Python自學心得30天系列 第 25

IOS、Python自學心得30天 Day-25 Firebase銜接Python-3

  • 分享至 

  • xImage
  •  

前言:
在試做的時候分成兩個檔案
firebase 設定的時候好像只能用一次
不然會報錯
所以我寫在 def 裡
用同個PY檔案去跑

程式碼:

import time
import sys
import numpy as np
from firebase import firebase
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.models import load_model
from tensorflow.python.keras.preprocessing import image

def downloadFireBase():
    import pyrebase
    import os
    import time
    from firebase import firebase

    config = {
        "apiKey": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "authDomain": "XXXXXXXXXXXXXXXXXX.firebaseio.com",
        "databaseURL": "https://XXXXXXXXXXXXXXXXXX.firebaseio.com",
        "projectId": "XXXXXXXX",
        "storageBucket": "XXXXXXXX.appspot.com",
        "messagingSenderId": "數字",
        "appId": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    }

    firebase = pyrebase.initialize_app(config)
    storage = firebase.storage()
    my_image = "dog.jpg"

    # Upload Image
    # storage.child(my_image).put(my_image)


    # Get url of image
    auth = firebase.auth()
    email = "XXXXXXXX@gmail.com"
    password = "XXXXXXXXXX"
    user = auth.sign_in_with_email_and_password(email, password)

    time.sleep(4)
    url = storage.child(my_image).get_url(user['idToken'])
    # Download Image
    storage.child(my_image).download(filename="dog.jpg", path=os.path.basename(my_image))
    print(url)

def detectPhoto():
    import time
    import sys
    import numpy as np
    from firebase import firebase
    from tensorflow.python.keras import backend as K
    from tensorflow.python.keras.models import load_model
    from tensorflow.python.keras.preprocessing import image


    key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    authentication = firebase.FirebaseAuthentication(key, 'XXXXXXXX@gmail.com')
    firebase.authentication = authentication
    user = authentication.get_user()
    firebase = firebase.FirebaseApplication('https://XXXXXXXXXXXXXXXXXX.firebaseio.com/', authentication=authentication)
    resultAcc = firebase.get('/dogAcc', '')
    print(resultAcc)
    resultName = firebase.get('/dogName', '')
    print(resultName)
    # 從參數讀取圖檔路徑
    files = ["dog.jpg"]
    print(files)
    print("=============================")
    # 載入訓練好的模型
    net = load_model('model-resnet50-final-11.h5')

    cls_list = [...]

    # 辨識每一張圖
    for f in files:
        img = image.load_img(f, target_size=(300, 300))
        if img is None:
            continue
        x = image.img_to_array(img)
        x = np.expand_dims(x, axis = 0)
        pred = net.predict(x)[0]
        top_inds = pred.argsort()[::-1][:1]
        print(f)
        for i in top_inds:
            print('準確率: {:.2%}   {}'.format(pred[i], cls_list[i]))
            firebase.put('/dogAcc','Acc' , '{:.2%}'.format(pred[i]))
            firebase.put('/dogName','Name' , '{}'.format(cls_list[i])) 
            firebase.put('/DetectBool', 'Bool', 'False')
        #firebase.delete("/dogDetail",'AC')

key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
authentication = firebase.FirebaseAuthentication(key, 'XXXXXXXX@gmail.com')
firebase.authentication = authentication
user = authentication.get_user()
firebase = firebase.FirebaseApplication('https://XXXXXXXXXXXXXXXXXX.firebaseio.com/', authentication=authentication)
while True:
    if firebase.get('/DetectBool', 'Bool') == "True":
        print("前端偵測開啟")
        if firebase.get('/DownloadBool', 'Bool') == "False":
            firebase.put('/DownloadBool', 'Bool', 'True')
            print("等候照片上傳完畢...")
            time.sleep(8)
            downloadFireBase()
            print("照片下載成功!")
            firebase.put('/DownloadBool', 'Bool', 'False')
            if firebase.get('/DetectBool', 'Bool') == "True":
                print("前端偵測開啟,開始辨識...")
                detectPhoto()
                print("資料上傳完畢!")
    else:
        time.sleep(4)
        print("前端偵測關閉中...")

上一篇
IOS、Python自學心得30天 Day-24 Firebase銜接Python-2
下一篇
IOS、Python自學心得30天 Day-26 Firebase部分
系列文
IOS、Python自學心得30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言